﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Musicman.Business;
using System.IO;

namespace MusicmanWeb.Custom
{
    public class ProfilePictureHandler : IHttpHandler
    {
        #region IHttpHandler Members

        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            byte[] imageData = null;
            long userID = 0;
            if (!String.IsNullOrEmpty(context.Request["personid"]))
            {
                userID = Int64.Parse(context.Request["personid"]);
            }
            else if (context.User.Identity.IsAuthenticated)
            {
                userID = Int64.Parse(context.User.Identity.Name);
            }
            imageData = UserManager.Instance.LoadProfilePicture(userID);

            if (imageData == null)
            {
                FileStream fs = null;
                MemoryStream ms = null;
                try
                {
                    string filePath = "";
                    Musicman.Common.Entities.User user = UserManager.Instance.GetUser(userID);
                    if (user.PersonSex == Musicman.Common.Entities.Sex.Male)
                    {
                        filePath = context.Server.MapPath("~/Images/john_doe.jpg");
                    }
                    else
                    {
                        filePath = context.Server.MapPath("~/Images/jane_doe.jpg");
                    }
                    fs = File.Open(filePath, FileMode.Open, FileAccess.Read);
                    ms = new MemoryStream();
                    const int buffersize = 1024 * 16;
                    byte[] buffer = new byte[buffersize];
                    int count = fs.Read(buffer, 0, buffersize);
                    while (count > 0)
                    {
                        ms.Write(buffer, 0, count);
                        count = fs.Read(buffer, 0, buffersize);
                    }
                    imageData = ms.ToArray();
                    ms.Close();
                    fs.Close();
                }
                catch 
                {
                    if (fs != null) fs.Close();
                    if (ms != null) ms.Close();
                }
            }
            if (imageData != null)
            {
                context.Response.AddHeader("Content-Type", "image/jpeg");
                context.Response.OutputStream.Write(imageData, 0, imageData.Length);
            }
        }

        #endregion
    }
}
